package com.gxkj.common.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;

public class WebUtil {
		public static  final Logger LOG = LoggerFactory.getLogger(WebUtil.class);
		/**
		 * 获取包含context的完整路径：http://127.0.0.1/xxx ("/xxx"为contextPath)
		 * @param request
		 * @return
		 */
		public static String getBasePath(HttpServletRequest request){
			String basePath ="null";

			String urlStr = request.getRequestURL().toString();
			basePath = urlStr.substring(0,urlStr.indexOf(request.getContextPath())); 
			return basePath+request.getContextPath();
		}
		/**
		 * 获取“WEB-INF”之前的绝对路径
		 * @return 
		 */
		public static String getBasePath() {
			URL url = WebUtil.class.getResource("WebUtil.class");
			String path = url.getPath();
			try {
				path = java.net.URLDecoder.decode(path,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			int index = path.lastIndexOf("WEB-INF");
			if(index < 0 ){
				index =  path.lastIndexOf("target");
			}
			path = path.substring(0, index);

			if(path.startsWith("file:/")){
				path = path.substring(5, path.length());
			}
			if(path.indexOf(":")>0)
				path = path.substring(1, path.length());
// 			System.out.println("getBasePath:"+path);
			LOG.info("getBasePath:"+path);
			return path;
		}
		
		

		
		/**
		 * 获取URL中？号后的参数
		 * @param url
		 *           URL对象
		 * @param key
		 *           URL query key
		 * @return value
		 */
		public static String getParameter(URL url,String key){
			return UtilString.string2map(url.getQuery(),"&").get(key);
		}
		/**
		 * 把一个符合URL格式的字符串转换成URL对象
		 * @param string
		 * @return url(URL对象) 非URL对象返回null
		 * @throws MalformedURLException
		 */
		public static URL string2url(String string){
			try {
				return new URL(string);
			} catch (Exception e) {
				return null;
			}
		}

		
		public static void main(String[] arg){
			System.out.println(getBasePath());  //  /E:/workspace/testcms/WebRoot/
		}
	
}
